package lib;

public class Geometry {
	/** the polygon area */
	public double getArea(int[] xs, int[] ys) {
		double res = 0;
		for(int i = 1; i < xs.length - 1; i++) {
			res += (xs[i] - xs[0])*(ys[i + 1] - ys[0]) - (xs[i + 1] - xs[0])*(ys[i] - ys[0]);
		}
		
		return Math.abs(res)/2.0;
	}
	
	/** the distance between line that connects A with B, and point C */
	public double getPointLineDist(int[] ca, int[] cb, int[] cc) {
		double area = getArea(new int[]{ca[0], cb[0], cc[0]}, new int[]{ca[1], cb[1], cc[1]});
		double abDist = Math.sqrt((ca[0] - cb[0])*(ca[0] - cb[0]) + (ca[1] - cb[1])*(ca[1] - cb[1]));
		
		if(ca[0] == cb[0] && ca[1] == cb[1]) {
			System.out.println("something's wrong here: getPointLineDist();");
			return cc[1];
		}
		
		return area*2.0/abDist;
	}
	
	/** get the line to line intersection given the equations of lines as a[i]*x + b[i]*y + c[i] = 0, and return new double[]{x, y}; */
	public double[] getLineIntersection(int[] as, int[] bs, int[] cs) {
		double det = as[0]*bs[1] - as[1]*bs[0];
		if(Math.abs(det) < 1e-9) {
			System.out.println("something's wrong here: getLineIntersection();");
		}
		double x = (bs[1]*cs[0] - bs[0]*cs[1])/det;
		double y = (as[0]*cs[1] - as[1]*cs[0])/det;
		
		return new double[] {x, y};
	}
	
	public static void main(String[] args) {
		Geometry app = new Geometry();
		System.out.println(app.getArea(new int[]{0, 1, 2}, new int[]{0, 2, 1}) + " compared to 1.5");
		System.out.println(app.getArea(new int[]{0, 1, 2}, new int[]{0, 0, 1}) + " compared to 0.5");
		
		System.out.println(app.getPointLineDist(new int[]{0, 0}, new int[]{1, 1}, new int[]{3, 0}) + " compared to " + (1.5*Math.sqrt(2)));
		System.out.println(app.getPointLineDist(new int[]{0, 0}, new int[]{1, 1}, new int[]{3, 3}) + " compared to 0");
		System.out.println(app.getPointLineDist(new int[]{0, 0}, new int[]{0, 1}, new int[]{3, 3}) + " compared to 3");
		
		double[] li = app.getLineIntersection(new int[]{1, 1}, new int[]{-1, 1}, new int[]{0, 1});
		System.out.println(li[0] + " : " + li[1] + " compared to 0.5 : 0.5");
		li = app.getLineIntersection(new int[]{0, 1}, new int[]{1, 0}, new int[]{0, 0});
		System.out.println(li[0] + " : " + li[1] + " compared to 0 : 0");
	}
}
